import { BadRequestException, Injectable } from '@nestjs/common';
import { PrismaService } from 'prisma/prisma.server';
import { AdminDto, Register, Update } from './admin.dto';
import { verify } from 'src/utils/captcha';
import { AuthService } from 'src/Auth/auth.service';
import { Result } from 'src/result/Result';
import { filterEmptyValuesInObject, nowDateTime } from 'src/utils';

@Injectable()
export class AdminService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly auth: AuthService,
  ) {}

  async Login({ phone, username, password, captcha, uuid }: AdminDto) {
    if (await verify({ uuid, captcha })) {
      const where = phone ? { phone, password } : { username, password };
      const user = await this.prisma.users.findFirst({
        where: { ...where },
        select: { username: true, phone: true, email: true, id: true },
      });
      if (Object.values(user || {}).length) {
        const token = this.auth.generate(user);
        return Result.Ok(
          { token, username: user.username },
          `登录成功， 欢迎用户：${user.username}`,
        );
      } else throw new BadRequestException('用户名或密码错误');
    } else throw new BadRequestException('验证码错误或失效');
  }

  async register({ username, phone, password }: Register) {
    const user = await this.prisma.users.findFirst({ where: { phone } });
    const result = { message: '', count: null };
    if (user && Object.values(user).length) {
      result.message = '注册失败, 已有相同手机号';
    } else {
      result.message = '注册成功， 请登录';
      result.count = await this.prisma.users.createMany({
        data: { username, phone, password },
      });
    }
    return result;
  }

  async Logout(token: string) {
    const msg = await this.auth.del(token);
    return Result.ok('', msg);
  }

  async updateAvatar(id: number, UserInfo: Update) {
    const userInfo = filterEmptyValuesInObject({ ...UserInfo });
    return this.prisma.users.update({
      where: {
        id,
      },
      data: {
        ...userInfo,
        updated_at: nowDateTime(),
      },
    });
  }

  getInfo(id: number) {
    return this.prisma.users.findFirst({
      where: {
        id,
      },
    });
  }
}
